package com.lyz.anli;

import java.util.Arrays;

/**
 * @ClassName De9fcz
 * @Description 二分查找
 * @Author 2214361854
 * @Date 2022/2/21 11:58
 * @Version 1.0
 */
public class De9fcz {
    public static void main(String[] args) {
        int[] arr = {1,42,7,23,20};
        int data = 20;
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));
        System.out.println(data+",索引："+binarySearch(arr, data));
    }
    public static int binarySearch(int[] arr,int data){
        //左索引
        int left = 0;
        //右索引
        int right = arr.length-1;
        while(left<=right){
            //中间索引
            int minddle = (left+right)/2;
            //值大于 找右边，反之亦然
            if (data>arr[minddle]) {
                //移动中间索引
                left = minddle + 1;
            }else if (data<arr[minddle]) {
                right = minddle - 1;
            }else {
                return minddle;
            }
        }
        return -1;
    }
}
